package ro.gateway.aida.autodates;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Timer;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import ro.gateway.aida.db.PersistenceManager;
import ro.gateway.aida.obj.db.SystemPropertyDB;

/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: Jul 6, 2004
 * Time: 11:14:44 AM
 * To change this template use File | Settings | File Templates.
 */
public class StatusAutomationStarter$Servlet extends HttpServlet {
	static boolean started = false;

	public void init() throws ServletException {
		super.init();
		if (!isSystemStatusAutomationON()) return;
		try {
			startUP(getServletContext());
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public static void startUP(ServletContext application) throws Exception {
		System.out.println("Starting StatusAutomationTaskManager");
		long task_sleep_period = 1000 * 3600 * 24;
//		long task_sleep_period = 1000 * 60;

		// daily job
		StatusAutomation$Task daily_task = new StatusAutomation$Task(application);
		Timer daily_worker = new Timer(false);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss(SSSS)");
		Calendar daily_startupdate = getNextDay();
		System.out.println("------- Daily Task scheduled@" + sdf.format(daily_startupdate.getTime()));
		daily_worker.scheduleAtFixedRate(daily_task, daily_startupdate.getTime(), task_sleep_period);

		// startup job
		StatusAutomation$Task startup_task = new StatusAutomation$Task(application);
		Timer startup_worker = new Timer(false);
		Calendar startupdate = getNext30Seconds();
		System.out.println("------- Startup Task scheduled@" + sdf.format(startupdate.getTime()));
		startup_worker.schedule(startup_task, startupdate.getTime());


		// store daily_timer and daily_task in application context
		application.setAttribute(StatusAutomation$Task.TASK_BEAN_NAME, daily_task);
		application.setAttribute(StatusAutomation$Task.TIMER_BEAN_NAME, daily_worker);
		application.setAttribute(StatusAutomation$Task.STARTUP_TIMER_BEAN_NAME, startup_worker);

		started = true;
		System.out.println("StatusAutomationTaskManager started");
	}

	public boolean isTaskRunning() {
		StatusAutomation$Task daily_task = (StatusAutomation$Task) getServletContext()
			  .getAttribute(StatusAutomation$Task.TASK_BEAN_NAME);
		return (daily_task != null && daily_task.isRunning());
	}

	public static void shutdown(ServletContext application) {
		System.out.println("Shuting down StatusAutomationTaskManager");
		StatusAutomation$Task task = (StatusAutomation$Task) application
			  .getAttribute(StatusAutomation$Task.TASK_BEAN_NAME);
		if (task != null) {
			while (task.isRunning()) {
				try {
					System.out.println("Waiting for StatusAutomationTask to finnish the job!");
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
				}
			}
			task.cancel();
		}
		System.out.println("StatusAutomationTaskManager down");
	}

	public void destroy() {
		if (!started) return;
		shutdown(getServletContext());
		started = false;
		super.destroy();
	}

	private static Calendar getNextDay() {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.MILLISECOND, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.HOUR, 0);
		cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH) + 1);
		return cal;
	}

	private static Calendar getNext30Seconds() {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.MILLISECOND, 0);
		cal.set(Calendar.SECOND, cal.get(Calendar.SECOND) + 30);
//		cal.set(Calendar.MINUTE, cal.get(Calendar.MINUTE));
		return cal;
	}

	public boolean isSystemStatusAutomationON() {
		boolean automation_on = false;
		try {
			String s_automation_on = SystemPropertyDB.getManager(PersistenceManager.tokenLookup(getServletContext()))
				  .getProperty("statusautomation");
			automation_on = s_automation_on != null && s_automation_on.equals("true");
		} catch (SQLException e) {
			e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
		}
		return automation_on;
	}
}
